#include "board.h"

Board::Board(QWidget*p):QWidget(p)
{
    setWindowTitle("Legami");
    setAutoFillBackground(true);
    QPalette pal = this->palette();
    pal.setColor(QPalette::Window, Qt::black); //QPalette::Window indica che voglio cambiare il colore di sfondo
    this->setPalette(pal);

    horizontal_bar_logo();
    horizontal_bar_choice();

    QVBoxLayout* mainLayout = new QVBoxLayout;

    // crea menu
    QMenuBar* menuBar = new QMenuBar(0);
    QMenu* fileMenu = menuBar->addMenu(tr("File"));
    QAction* exitAction = fileMenu->addAction(tr("Close Legami"));

    QMenu* viewMenu = menuBar->addMenu(tr("&View"));
    QAction* fullScreenAction = viewMenu->addAction(tr("Full screen"));
    QAction* normalViewAction = viewMenu->addAction(tr("Normal view"));

    // connessione signal-slot
    connect(exitAction, SIGNAL(triggered()), this, SLOT(close()));
    connect(fullScreenAction, SIGNAL(triggered()), this, SLOT(showFullScreen()));
    connect(normalViewAction, SIGNAL(triggered()), this, SLOT(showNormal()));

    mainLayout->setMenuBar(menuBar);
    mainLayout->addWidget(hgl);
    mainLayout->addWidget(hgc);
    setLayout(mainLayout);

    setFixedSize(470,300);
    viewMenu->setDisabled(true);

    //invocazione database
    try {init_db();}
    catch(database_error){
        QMessageBox::about(this,"Errore Database","<p>Database al momento non disponibile</p>Riprovare in un secondo momento.");
        user->setEnabled(false);
        amm->setEnabled(false);
    }
    catch(wrongdatabase_error){
        QMessageBox::about(this,"Errore Database","Database corrotto o non esistente");
        user->setEnabled(false);
        amm->setEnabled(false);
    }
    catch(logic_error){
        QMessageBox::about(this,"Attenzione!","Database vuoto.");
    }
}

Board::~Board(){
    delete logo;
}

void Board::closeEvent(QCloseEvent* event){
    if(db.isOpen())
        db.close();
    event->accept();
}

void Board::horizontal_bar_logo()
{
    hgl = new QGroupBox();
    QGridLayout* layout = new QGridLayout;

    logo=new Logo("img/lwb.jpg", this);

    close=new QPushButton("Exit",this);
    connect(close,    SIGNAL(clicked()),  this,   SLOT(close()));
    logo->setFixedSize(300,300);
    close->setFixedSize(140,40);
    layout->addWidget(logo, 0, 2);
    layout->addWidget(close, 0, 3, Qt::AlignTop);

    hgl ->setLayout(layout);
}

void Board::horizontal_bar_choice()
{
    hgc = new QGroupBox();
    QHBoxLayout* lo = new QHBoxLayout;

    amm= new QPushButton("Amministratore", this);
    lo->addWidget(amm);

    user= new QPushButton("Login Utente", this);
    lo->addWidget(user);

    connect(user, SIGNAL(clicked()), this, SLOT(tabba_user()));
    connect(amm, SIGNAL(clicked()), this, SLOT(tabba_amm()));

    hgc->setLayout(lo);
}

void Board::init_db() throw(logic_error, database_error, wrongdatabase_error){
    db = QSqlDatabase::addDatabase("QSQLITE");
    //crea una nuova connessione
    db.setDatabaseName("database/user.db"); //cerca database in cartella database
    if(!db.open()){
        qCritical() << db.lastError();
        throw database_error();
    }
    if(db.record("utenti").isEmpty())
        throw wrongdatabase_error();

    gestore= new Legami(&db);
    //----UTENTI/ACCOUNT-----
    QString birthday;
    QString new_school;
    QString old_school;
    QString link1;
    QString link2;
    Account* acc;

    QSqlQuery query(db);
    query.exec("Select aeb,username,password,nome,cognome,sesso from utenti");
    if(!query.next()) //tabella utenti vuota
        throw logic_error();
    else{
        query.previous();   //son andato al next per fare il primo controllo, torno indietro senno' mi salta il primo utente
        while(query.next()){
        QString usern= query.value(1).toString();
        QSqlQuery subquery(db);
        subquery.prepare("Select distinct birthday,new_school, old_school, link1, link2 from info where username= :usern");
        subquery.bindValue(":usern", usern);
        subquery.exec();
        while(subquery.next()){
            birthday= subquery.value(0).toString();
            new_school= subquery.value(1).toString();
            old_school= subquery.value(2).toString();
            link1= subquery.value(3).toString();
            link2= subquery.value(4).toString();
        }   // qui ho birthday, new_school, old_school
        QSqlQuery subquery_b(db);
        subquery_b.prepare("Select interest from info where username= :usern");
        subquery_b.bindValue(":usern", usern);
        subquery_b.exec();
        QVector<QString> interests;
        while(subquery_b.next()){
            QString interest= subquery_b.value(0).toString();
            interests.push_back(interest);
        }   // uscito da qui ho il vettore di interessi
        int aeb= query.value(0).toInt();
        QString pwd= query.value(2).toString();
        QString name= query.value(3).toString();
        QString surname= query.value(4).toString();
        int gender= query.value(5).toInt();
        //inizio a caricare l'user
        Username* un= new Username(name, surname, usern, pwd,gender);
        Info* info= new Info(birthday, interests, new_school, old_school, link1, link2);
        Profilo* pr= new Profilo(info);
        if(aeb==0) acc= new Account(un, pr);
        else if (aeb==1) acc= new BusinessAccount(un, pr);
        else acc= new ExecutiveAccount(un,pr);
        //a questo punto ho creato l'account
        gestore->add(acc);
        }
    }
    //----FINE UTENTI/ACCOUNT----
    //----GRUPPI----
    QSqlQuery query_gruppo(db);
    query_gruppo.exec("Select distinct id_group, nome, proprietario from gruppi");
    while(query_gruppo.next()){
        QString id=query_gruppo.value(0).toString();
        QString nome= query_gruppo.value(1).toString();
        QString owner= query_gruppo.value(2).toString();
        Gruppo* gr= new Gruppo(id,nome,owner);
        gestore->addgruppo(gr);
    }
    //----FINE GRUPPI----
    gestore->fillUsers();   //contatti per ogni account!
    gestore->fillGroups();  //membri per ogni gruppo
}

void Board::tabba_user(){
    user->setEnabled(false);
    user_amm= false;                            //user_amm = 0 = user!
    tabbed= new Tabwidget(user,amm,user_amm);   //la finestra degli utenti
    tabbed->setWindowTitle("Utente di Legami");
    tab = new TabUser(tabbed,user,gestore,&db);
    tabbed->addTab(tab,"Login Utente");
    tabbed->show();
}

void Board::tabba_amm(){
    amm->setEnabled(false);
    user_amm=true;                              //user_amm = 1 = amm
    tabbed= new Tabwidget(user,amm,user_amm);   //finestra per l'amministrazione
    tabbed->setWindowTitle("Amministrazione");
    tab = new TabAmm(tabbed,amm,gestore,&db);
    tabbed->addTab(tab,"Login Amministratore");
    tabbed->show();
}
